﻿
using System;
using System.Net;
using System.Text;
using System.Windows;
using Newtonsoft.Json;
using System.IO;

namespace eLearning.Util
{
    public class WebServiceUtil
    {
        private static string result;

        public static string WebRequest(object model, string url)
        {
            string json = JsonConvert.SerializeObject(model);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            //Set header
            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            //menangani respon yang diberikan oleh server ketika menjalankan method UploadStringAsync()
            client.UploadStringCompleted += new UploadStringCompletedEventHandler(request_UploadStringCompleted);

            try
            {
                //melakukan UploadString dengan method POST secara asynchronous
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }

            return result;
        }

        private static void request_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled && e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                } else 
                {
                    result = e.Result;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

    }
}
